//
//  OAuthViewController.swift
//  WKweiBo
//
//  Created by 阿拉斯加的狗 on 15/12/7.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {

    //创建webView
    private lazy var webView = UIWebView()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //加载页面
        webView .loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
        
    }

    //监听方法
    @objc private func close(){
    
        //返回上一层
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    
    @objc private func autoFull(){
    
        let js = "document.getElementById('userId').value = '1281433811@qq.com';" +
        "document.getElementById('passwd').value = 'z13egist80';"
//        let js = "document.getElementById('userId').value = 'daoge10000@sina.cn';" +
//        "document.getElementById('passwd').value = 'qqq123';"
        
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    
    }
    
    //设置界面
    override func loadView() {
        
        view = webView

        //设置背景颜色
        view.backgroundColor = UIColor.whiteColor()
        
        //设置代理
        webView.delegate = self
        
        //设置导航栏
        title = "登陆新浪微博"
        
        //设置左右两边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登陆", style: .Plain, target: self, action: "autoFull")
    }


}

// MARK: - 代理方法的监听
extension OAuthViewController: UIWebViewDelegate{

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //判断访问主机是否为百度
        guard let url = request.URL where url.host == "www.baidu.com" else{
        
            return true
            
        }
        
        //获取百度中的code地址
        guard let query = url.query where query.hasPrefix("code=") else {
        
            print("取消授权")
            
            close()
            
            return false
        }
        
        //获取code
        let code = query.substringFromIndex("code=".endIndex)
        
        print(query)
        print("授权码是 " + code)
        
        //加载 accessToken
        
            UserAccountViewModel.sharedUserAccount.loadAccessToken(code, finished: { (isSuccessed) -> () in
                
                if isSuccessed {
                
                    print("成功")
                    
                    print(UserAccountViewModel.sharedUserAccount.account)
                    
                    // dismissViewControllerAnimated 方法不会立即将控制器销毁
                    self.dismissViewControllerAnimated(false) {
                        
                        // 通知中心是同步的 - 一旦发送通知，会先执行监听方法，直接结束后，才执行后续代码
                        NSNotificationCenter.defaultCenter().postNotificationName(WKSwitchRootViewControllerNotification, object: "welcome")
                    }
                
                }else{
                    
                    SVProgressHUD.showInfoWithStatus("您的网速不给力")
                    
                    delay(0.5) { self.close() }
                    
                    print("失败")
                    
                }
            })
            return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }
    
}